{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Analyze a dataset on the Hub"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the Quickstart, you were introduced to various endpoints for interacting with datasets on the Hub. One of the most useful ones is the `/parquet` endpoint, which allows you to get a dataset stored on the Hub and analyze it. This is a great way to explore the dataset, and get a better understanding of it's contents.\n",
    "\n",
    "To demonstrate, this guide will show you an end-to-end example of how to retrieve a dataset from the Hub and do some basic data analysis with the Pandas library."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get a dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The [Hub](https://huggingface.co/datasets) is home to more than 200,000 datasets across a wide variety of tasks, sizes, and languages. For this example, you'll use the [`codeparrot/codecomplex`](https://huggingface.co/datasets/codeparrot/codecomplex) dataset, but feel free to explore and find another dataset that interests you! The dataset contains Java code from programming competitions, and the time complexity of the code is labeled by a group of algorithm experts. \n",
    "\n",
    "Let's say you're interested in the average length of the submitted code as it relates to the time complexity. Here's how you can get started. \n",
    "\n",
    "Use the `/parquet` endpoint to convert the dataset to a Parquet file and return the URL to it:\n",
    "\n",
    "<inferencesnippet>\n",
    "<python>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "API_URL = \"https://datasets-server.huggingface.co/parquet?dataset=codeparrot/codecomplex\"\n",
    "def query():\n",
    "    response = requests.get(API_URL)\n",
    "    return response.json()\n",
    "data = query()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</python>\n",
    "<js>\n",
    "```js\n",
    "import fetch from \"node-fetch\";\n",
    "async function query(data) {\n",
    "    const response = await fetch(\n",
    "        \"https://datasets-server.huggingface.co/parquet?dataset=codeparrot/codecomplex\",\n",
    "        {\n",
    "            method: \"GET\"\n",
    "        }\n",
    "    );\n",
    "    const result = await response.json();\n",
    "    return result;\n",
    "}\n",
    "query().then((response) => {\n",
    "    console.log(JSON.stringify(response));\n",
    "});\n",
    "```\n",
    "</js>\n",
    "<curl>\n",
    "```curl\n",
    "curl https://datasets-server.huggingface.co/parquet?dataset=codeparrot/codecomplex \\\n",
    "        -X GET\n",
    "```\n",
    "</curl>\n",
    "</inferencesnippet>\n",
    "\n",
    "```json\n",
    "{\"parquet_files\": \n",
    "    [\n",
    "        {\"dataset\": \"codeparrot/codecomplex\", \"config\": \"default\", \"split\": \"train\", \"url\": \"https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet\", \"filename\": \"0000.parquet\", \"size\": 4115908}\n",
    "    ], \n",
    " \"pending\": [], \"failed\": [], \"partial\": false\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read dataset with Pandas"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the URL, you can read the Parquet file into a Pandas DataFrame:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "url = \"https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet\"\n",
    "df = pd.read_parquet(url)\n",
    "df.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|                                               src | complexity |                         problem |       from |\n",
    "|--------------------------------------------------:|-----------:|--------------------------------:|-----------:|\n",
    "| import java.io.*;\\nimport java.math.BigInteger... |  quadratic |     1179_B. Tolik and His Uncle | CODEFORCES |\n",
    "| import java.util.Scanner;\\n \\npublic class pil... |     linear |                 1197_B. Pillars | CODEFORCES |\n",
    "| import java.io.BufferedReader;\\nimport java.io... |     linear | 1059_C. Sequence Transformation | CODEFORCES |\n",
    "| import java.util.*;\\n\\nimport java.io.*;\\npubl... |     linear |                  1011_A. Stages | CODEFORCES |\n",
    "| import java.io.OutputStream;\\nimport java.io.I... |     linear |    1190_C. Tokitsukaze and Duel | CODEFORCES |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate mean code length by time complexity"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas is a powerful library for data analysis; group the dataset by time complexity, apply a function to calculate the average length of the code snippet, and plot the results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.groupby('complexity')['src'].apply(lambda x: x.str.len().mean()).sort_values(ascending=False).plot.barh(color=\"orange\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"flex justify-center\">\n",
    "    <img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets-server/codecomplex.png\"/>\n",
    "</div>"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
